import * as _ from 'lodash';
import { Injectable } from '@nestjs/common';
import { UserInfo } from '../models/socket-io-model';

@Injectable()
export class SocketService {
    private current_index = 1;
    private _dict: { [code: string]: number } = {};
    private _list: { [index: number]: UserInfo } = {};

    getNewIndex() {
        return this.current_index++;
    }

    /** 注册新用户 */
    regNewUser(socket_id: string) {
        let _user_index = this.current_index++;
        let _user_info: UserInfo = { id: _user_index, socket_code: socket_id };
        this._dict[socket_id] = _user_index;
        this._list[_user_index] = _user_info;
        return _user_info
    }

    /** 用户离线 */
    userLeave(socket_id: string) {
        let _user_index = this._dict[socket_id];
        if (_user_index) {
            delete this._dict[socket_id];
            delete this._list[_user_index];
        }
        return _user_index;
    }

    getUser(id_or_socketid: string | number): UserInfo | undefined {
        let user_info: UserInfo | undefined = undefined;
        if (typeof id_or_socketid == "number") {
            user_info = this._list[id_or_socketid];
        }
        else {
            let user_index = this._dict[id_or_socketid];
            if (user_index) {
                user_info = this._list[user_index];
            }
        }
        return user_info;
    }

    getUserList(): UserInfo[] {
        return _.map(
            this._list,
            item => _.pick(item, ['id', 'nick_name', 'socket_code'])
        );
    }

    changeNickName(socket_id: string, nick_name: string) {
        let user_info = this.getUser(socket_id);
        if (user_info) {
            user_info.nick_name = nick_name;
        }
        return user_info;
    }
}
